
var System = { 
    
    /**
    * Check how long a user has been idle,
    * if they've been idle more than idleTime allows,
    * set them as away.
    *
    * @author Benjamin Hutchins
    **/
   idle: function() {
      var timeStamp = new Date().getTime() - (idleTime * 60 * 1000);
      if (Status.lastIM < timeStamp && typeof(Status) != 'undefined' && Status.state == 0) {
         Status.set(1, Languages.get('away'));
         Status.wasSetAutoAway = true;
      }
   },
   
   ping: function(user) {
      
       var myXhr = new XHR({method: 'post', 
      						onSuccess: function() {
							            	 var i;

            /*if((typeof xh.status != 'undefined' && xh.status!=200) || xh.responseText == 'not_logged_in') {
               alert ("logout");
               return;
            }*/
            if(this.response['text'] == 'not_logged_in') {
               alert ("logout");
               return;
            }
                   
            if(trim(this.response['text']).length == 0) return;

            var response = Json.evaluate(this.response['text']);

            var data;
            var messageCount = (typeof(response.messages) !== 'undefined' ? response.messages.length : 0);
            for(i=0; i<messageCount; i++) {
               var sender = new User (response.messages[i].sender, response.messages[i].sendername);
               data = response.messages[i].message;
               
               var myself = new User (user, response.messages[i].recipient);
             
               var message = new Message (sender, myself, data);
               
               var winId = null;
               try { 
               		winId = imManager.windows[sender.getId()].getId(); 
               } 
               catch(e) { /*alert (e);*/};
            
               if(!$(winId)) {
                  // if there's no window for this user, we create it
                  imManager.create(myself, sender);
               } /*else {
                  if(!imManager.windows[who].detached && !window['IM'].windows[who].isVisible()) {
                     imManager.windows[who].show();
                     setTimeout("scrollToBottom('" + imManager.windows[who].getId() + "dialogbox')", 125);
                  }
               }*/
               
               // the message is sent tot the window
               imManager.windows[sender.getId()].sendResult(message, null);
	
               
               /*
               if(!initial) {
                  if(curIM.innerHTML.toLowerCase().replace(/<\S[^>]*>/g, '').indexOf(user.toLowerCase()+': (' + Languages.get('autoreply').toLowerCase() + ')') == -1 && typeof(Status) != 'undefined' && Status.state == 1 && who == from) {
                     var fontName    = $(winId + '_setFont').innerHTML;
                     var fontSize    = $(winId + '_setFontSize').innerHTML;
                     var fontColor   = $(winId + '_setFontColorColor').style.backgroundColor;
                     window['IM'].sendMessage(from, '(' + Languages.get('autoreply') + ') ' + Status.awayMessage, false, false, false, fontName, fontSize, fontColor);
                  }
                  
                  if(Windows.getFocusedWindow().getId() != window['IM'].windows[who].getId() && pulsateTitles == true) {
                     new Effect.Pulsate(window['IM'].windows[who].getId() + '_top');
                  }
            
                  if(titlebarBlinker == true && useBlinker == true) {
                     clearTimeout(blinkerTimer);
                     blinkerTimer = setTimeout("titlebarBlink('"+who+"', \""+data.replace(/\"/, '\"').replace(/<([^>]+)>/ig, '')+"\", 0, "+chatroom+")", blinkSpeed);
                  }
               }
               */
               curIM = null;
            }
            
            if(messageCount > 0) {
            	imManager.windows[sender.getId()].notify();
            }
            
            sender = null; data = null;
            var event = '';
            var eventCount = (typeof(response.events) !== 'undefined' ? response.events.length : 0);
            
            for(i=0; i<eventCount; i++) {
        		sender = new User (response.events[i].sender, response.events[i].sendername);
               	data = response.events[i].event;
               
                try { 
               		winId = imManager.windows[sender.getId()].getId(); 
                } 
                catch(e) { /*alert (e);*/};
            
                if($(winId)) {
               		var event = new Message (sender, myself, data);
               		imManager.windows[sender.getId()].sendResult(event, null);
                }
           }
            
              
         }}).send(urlToPing, "action=ping&caller="+user+"");
									
   },
   
   /**
    * store a terminated conversation
    */
   store: function (sender, recipient, content) {
   
   		var myXhr = new XHR({	method: 'post', 
      							onSuccess: function() {
							            // do nothing
							    }
						}).send(urlToPing, "action=store&caller="+sender+"&recipient="+recipient+"&content="+content);		
   },
   
   /**
    * update the list of current chats
    * @author : g. henson 
    */
   toggleChatList: function (user) {
   		var mylist = $(chatListid);
   		var userli = $(userlistPrefix+user.getId());
   		// si un element existe pour ce user
   		if (userli) {
   			// la conversation a ete fermee, on supprime l utilisateur de la liste
   			userli.remove (mylist);
   		}
   		else {
   			// sinon, on vient d ouvrir un chat, 
   			//on ajoute le user a la liste des chats en cours
	   		var chat = new Element ('li', {'id' : userlistPrefix+user.getId()});
	   		chat.innerHTML = '<a href=\'#\' onClick ="imManager.windows[\''+user.getId()+'\'].restore();">' + user.getName()+'</a>';
	   		chat.injectInside (mylist);
	   	}
	   	this.toggleNoChatElement();
   },
   
   /**
    * show or hide the no chat element
    * @author : g henson
    */
   toggleNoChatElement: function () {
        // si l element no chat existe
   		// et qu une conversation est en cours
   		if ($(noCurrentChat) && $(chatListid).getChildren().length>0){
   			// on le supprime
   			$(noCurrentChat).remove();
   		}
   		// si il n y a plus de conversation en cours
   		// on fait apparaitre no chat
   		else if (($(chatListid).getChildren().length==0) && !$(noCurrentChat)){
   			// sinon on le cree
   			var nochat = new Element ('div', {'id' : noCurrentChat});
   			nochat.innerHTML=Languages.get('no-current-chat');
   			nochat.injectInside($(moosmainid));
   		}	
   }
};
